package com.mask.mr.temp;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * ClassName TempMapper
 * Create by hx
 * Date 2021/9/29 2:10 下午
 */

class Temperature {
    // Map部分
    static class TempMapper extends Mapper<LongWritable, Text,Text, IntWritable> {
        public void map(LongWritable key,Text value,Context context) throws IOException, InterruptedException {
            //2010012325表示在2010年01月23日的气温为25度
            // 2014010114
            String line = value.toString();
            String year = line.substring(0,4);
            int temperature = Integer.parseInt(line.substring(8));
            context.write(new Text(year),new IntWritable(temperature));
        }
    }
    //Reduce 部分
    static class TempReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
        public void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException, InterruptedException {
//            int maxValue = Integer.MIN_VALUE;
//
//            for(IntWritable value : values) {
//                maxValue = Math.max(maxValue,value.get());
//            }
//            context.write(key,new IntWritable(maxValue));
            int minValue = Integer.MAX_VALUE;

            for(IntWritable value : values) {
                minValue = Math.min(minValue,value.get());
            }
            context.write(key,new IntWritable(minValue));
        }
    }
    // 主程序
    public static void main(String[] args) throws Exception {
        String inPath = "/Users/hx/Documents/massz.edu.cn/bigData/temperature/temperature.txt";
        String outPath = "/Users/hx/Documents/massz.edu.cn/bigData/temperature/min_output";
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJarByClass(Temperature.class);

        FileInputFormat.addInputPath(job,new Path(inPath));
        FileOutputFormat.setOutputPath(job,new Path(outPath));

        job.setMapperClass(TempMapper.class);
        job.setReducerClass(TempReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        boolean res = job.waitForCompletion(true);
        System.exit(res?0:1);
    }
}

